<template>
  <div class="app">
    <van-nav-bar title="助教预约" left-text="" left-arrow @click="backlink()" />
    <div class="zhujiaobox">
      <div class="zhujiaophotobox">
        <img v-lazy="zhujiaoinfo.photo" alt="" class="zhujiaophoto" />
      </div>
      <div class="zhujiaoinfobox">
        <div style="display: flex; justify-content: space-between">
          <div class="nickname">{{ zhujiaoinfo.nickname }}</div>
          <div style="display: flex; align-items: center">
            <div class="price">￥{{ zhujiaoinfo.zhujiao_price }}</div>
            <div style="font-size: 18px">/小时</div>
          </div>
        </div>
        <div class="level">{{ zhujiaoinfo.level }}</div>
      </div>
    </div>
    <div style="width: 90%; margin: 0 auto">
      <div style="display: flex; height: 25px; margin: 5px auto">
        <div class="cardtitle">预约信息</div>
      </div>
      <div class="yuyueinfobox">
        <van-field
          v-model="formdata.reservedate"
          is-link
          name="datePicker"
          label="预约日期"
          @click="showdatePicker = true"
        />
        <van-popup v-model:show="showdatePicker" position="bottom">
          <van-date-picker
            @confirm="onDateConfirm"
            @cancel="showdatePicker = false"
          />
        </van-popup>
        <van-field
          v-model="formdata.reservetime"
          is-link
          name="timePicker"
          label="预约时间"
          placeholder="请选择预约时间"
          @click="openpicker"
        />
        <van-popup v-model:show="showtimePicker" position="bottom">
          <van-picker
            title="预约时间"
            :columns="yuyuetimelist"
            @confirm="ontimeConfirm"
            @cancel="showtimePicker = false"
            v-model="defaultTime"
          />
        </van-popup>
        <van-field
          v-model="zhujiaoinfo.store_name"
          is-link
          readonly
          name="clubPicker"
          label="预约球房"
          placeholder="请选择预约球房"
        />
        <van-field
          v-model="formdata.reservemoney"
          is-link
          readonly
          name="clubPicker"
          label="预计金额"
        />
      </div>
      <van-button type="primary" round class="yuyuebtn" @click="postReservation"
        >确认预约</van-button
      >
    </div>
  </div>
</template>

<script>
import { showToast } from "vant";
import { useStore } from "@/store/index.js";
import { zhujiaoreservation } from "@/http/request.js";
export default {
  data() {
    return {
      formdata: {
        reservedate: "",
        reservetime: "",
        reservemoney: "",
      },
      showdatePicker: false,
      showtimePicker: false,
      zhujiaoinfo: {},
      yuyuetimelist: [],
      defaultTime: [],
    };
  },
  methods: {
    backlink() {
      this.$router.back();
    },
    getCurrentTimeFormatted() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, "0");
      const minutes = now.getMinutes().toString().padStart(2, "0");
      const seconds = now.getSeconds().toString().padStart(2, "0");
      return `${hours}:${minutes}:${seconds}`;
    },
    timeToMinutes(time) {
      const [hours, minutes, seconds] = time.split(":").map(Number);
      return hours * 60 + minutes + seconds / 60;
    },
    minutesToTime(minutes) {
      const hours = Math.floor(minutes / 60);
      const mins = Math.floor((minutes % 60).toFixed(2)).split(".")[0]; // 保留两位小数
      const secs = (((minutes % 60) % 1) * 60).toFixed(2).split(".")[0]; // 计算剩余的秒数
      return `${hours.toString().padStart(2, "0")}:${mins
        .toString()
        .padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
    },
    openpicker() {
      // 开始时间和结束时间数组
      const startTimeArray = this.yuyuetimelist[0];
      const endTimeArray = this.yuyuetimelist[1]; // 假设结束时间数组与开始时间数组一一对应

      // 获取当前时间的分钟数
      const currentTime = this.getCurrentTimeFormatted();
      const currentMinutes = this.timeToMinutes(currentTime);

      // 找到大于当前时间的最小开始时间和大于开始时间的最小结束时间
      let nextStartTimeIndex = startTimeArray.findIndex(
        (startTime) => this.timeToMinutes(startTime.value) > currentMinutes
      );
      if (nextStartTimeIndex === -1) {
        nextStartTimeIndex = startTimeArray.length - 1; // 如果没有找到大于当前时间的开始时间，则取最后一个开始时间
      }

      let nextEndTimeIndex = endTimeArray.findIndex(
        (endTime) =>
          this.timeToMinutes(endTime.value) >
          this.timeToMinutes(startTimeArray[nextStartTimeIndex].value)
      );
      if (nextEndTimeIndex === -1) {
        nextEndTimeIndex = endTimeArray.length - 1; // 如果没有找到大于开始时间的结束时间，则取最后一个结束时间
      }

      // 获取结果时间
      const nextStartTime = startTimeArray[nextStartTimeIndex];
      const nextEndTime = endTimeArray[nextEndTimeIndex];
      this.defaultTime = [nextStartTime.value, nextEndTime.value];
      this.showtimePicker = true;
    },
    onDateConfirm(value) {
      const selectedDate = new Date(value.selectedValues.join("/"));
      const today = new Date();
      const oneWeekLater = new Date(today);
      oneWeekLater.setDate(today.getDate() + 7); // 设置为一周后的日期
      // 确保选择的日期既不早于今天也不晚于一周后
      if (selectedDate >= today && selectedDate <= oneWeekLater) {
        this.formdata.reservedate = this.formatDate(selectedDate);
        this.showdatePicker = false;
      } else if (selectedDate < today) {
        showToast("选择的日期不能早于今天哦");
        this.showdatePicker = false;
      } else {
        showToast("选择的日期需在一周内哦");
        this.showdatePicker = false;
      }
    },
    ontimeConfirm(value) {
      if (this.isTimeOk(value.selectedValues)) {
        this.formdata.reservetime =
          value.selectedValues[0] + "-" + value.selectedValues[1];
        const index1 = this.yuyuetimelist[0].findIndex(
          (item) => item.value === value.selectedValues[0]
        );
        const index2 = this.yuyuetimelist[0].findIndex(
          (item) => item.value === value.selectedValues[1]
        );
        this.formdata.reservemoney =
          ((index2 - index1) / 2) * this.zhujiaoinfo.zhujiao_price;
      }
      this.showtimePicker = false;
    },
    postReservation() {
      const data = {};
      const store = useStore();
      const userinfo = store.getUserStoreinfo;
      data.user_id = userinfo.id;
      data.store_id = this.zhujiaoinfo.store_id;
      data.start_time = this.formdata.reservetime.split("-")[0];
      data.end_time = this.formdata.reservetime.split("-")[1];
      data.zhujiao_id = this.zhujiaoinfo.zhujiao_id;
      zhujiaoreservation(data).then((res) => {
        showToast(res.msg);
        if (res.code == 0) {
          const store = useStore();
          let yuyueorder = store.getYuyueingOrder;
          yuyueorder.zhujiao.push(res.data);
          store.setYuyueingOrder(yuyueorder);
          this.$router.push("/tableyuyueing");
        }
      });
    },
    initTime() {
      this.formdata.reservedate = this.formatDate(new Date());
      let freetime = [];
      if (this.zhujiaoinfo.starttime != null) {
        freetime = this.calctime(
          this.zhujiaoinfo.starttime,
          this.zhujiaoinfo.endtime,
          this.zhujiaoinfo.slice_time
        );
        for (var i = 0; i < freetime.length; i++) {
          this.yuyuetimelist.push({ text: freetime[i], value: freetime[i] });
        }
        this.yuyuetimelist = Array.from(
          { length: 2 },
          () => this.yuyuetimelist
        );
      }
    },
    isTimeOk(timeArray) {
      const [startTime, endTime] = timeArray;
      const currentDate = new Date();
      const startDate = new Date();
      const endDate = new Date();
      const [startHour, startMinute, startSecond] = startTime
        .split(":")
        .map(Number);
      const [endHour, endMinute, endSecond] = endTime.split(":").map(Number);
      startDate.setHours(startHour, startMinute, startSecond);
      endDate.setHours(endHour, endMinute, endSecond);
      if (startDate < currentDate) {
        showToast("开始时间不能早于当前时间哦");
        return false;
      }
      const index1 = this.yuyuetimelist[0].findIndex(
        (item) => item.value === startTime
      );
      const index2 = this.yuyuetimelist[0].findIndex(
        (item) => item.value === endTime
      );
      if (index1 > index2) {
        showToast("结束时间不能早于开始时间哦");
        return false;
      }
      return true;
    },
    sliceTime(startTime, endTime, sliceSize) {
      let result = [];
      let current = startTime;
      while (current < endTime) {
        result.push(current);
        let [hours, minutes, seconds] = current.split(":").map(Number);
        let nextMinutes = minutes + sliceSize;
        let nextHours = hours + Math.floor(nextMinutes / 60);
        nextMinutes = nextMinutes % 60;
        nextHours = nextHours % 24;
        current = `${String(nextHours).padStart(2, "0")}:${String(
          nextMinutes
        ).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
      }
      // 添加结束时间，确保包含 endTime
      result.push(endTime);
      return result;
    },
    calctime(startTime, endTime, sliceSize) {
      if (startTime > endTime) {
        const time1 = this.sliceTime(startTime, "23:30:00", sliceSize);
        const time2 = this.sliceTime("00:00:00", endTime, sliceSize);
        return time1.concat(time2);
      } else {
        return this.sliceTime(startTime, endTime, sliceSize);
      }
    },
    formatDate(date) {
      let d = new Date(date),
        month = "" + (d.getMonth() + 1),
        day = "" + d.getDate(),
        year = d.getFullYear();
      if (month.length < 2) month = "0" + month;
      if (day.length < 2) day = "0" + day;
      return [year, month, day].join("/");
    },
  },
  mounted() {
    this.initTime();
  },
  created() {
    this.zhujiaoinfo = JSON.parse(this.$route.params.zhujiaoinfo);
    this.zhujiaoinfo.starttime = this.zhujiaoinfo.business_hours.split("-")[0];
    this.zhujiaoinfo.endtime = this.zhujiaoinfo.business_hours.split("-")[1];
    this.zhujiaoinfo.slice_time = 30;
  },
};
</script>

<style scoped>
.app {
  height: 100vh;
  background-color: #f2f3f5;
}
.zhujiaobox {
  width: 90%;
  background-color: white;
  margin: 20px auto;
  border-radius: 15px;
  padding: 10px;
  display: flex;
  justify-content: space-around;
}
.zhujiaophotobox {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
}
.zhujiaophoto {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  object-position: center top;
}
.zhujiaoinfobox {
  width: 75%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
.nickname {
  font-size: 20px;
  font-weight: 600;
}
.price {
  font-size: 21px;
  font-weight: 600;
  color: #5e94fd;
}
.level {
  line-height: 25px;
  font-size: 18px;
}
.shuxian {
  color: #6196fd;
  font-size: 20px;
  font-weight: 600;
  line-height: 25px;
}
.cardtitle {
  font-size: 20px;
  font-weight: 600;
  line-height: 25px;
  margin-left: 5px;
}
.yuyueinfobox {
  width: 100%;
  background-color: white;
  height: 200px;
  border-radius: 20px;
  margin: 20px auto;
}
.yuyueinfobox .van-cell {
  border-top-left-radius: 25px !important;
  border-top-right-radius: 25px !important;
}
.yuyuebtn {
  margin-top: 15px;
  width: 100%;
}
</style>

<style>
.yuyueinfobox .van-cell .van-field__label {
  font-size: 17px !important;
  font-weight: 600 !important;
}
.yuyueinfobox .van-cell .van-cell__value {
  font-size: 17px !important;
}
</style>